package com.shuorikeji.huohuo.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.bean.SearchHistoryInfoBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;

public class SearchHisHotAdapter extends RecyclerView.Adapter<SearchHisHotAdapter.BaseViewHolder> {
    private final Context mContext;
    private List<SearchHistoryInfoBean> mData = new ArrayList<>();
    private ClickCallBack callBack;
    private int flag;//1搜索历史；2热门搜索

    public SearchHisHotAdapter(Context context, int flag, ClickCallBack callBackFlag) {
        this.mContext = context;
        this.callBack = callBackFlag;
        this.flag = flag;
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.search_history_hot_item_layout, parent, false);
        BaseViewHolder holder = new BaseViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, @SuppressLint("RecyclerView") int position) {
        if (flag == 2) {
            holder.ivDelete.setVisibility(View.GONE);
        } else {
            holder.ivDelete.setVisibility((mData.get(position).isDelete()) ? View.VISIBLE : View.GONE);
        }
        holder.tvContent.setText(mData.get(position).getSearch());
        holder.tvContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (callBack != null) {
                    callBack.onClick(1, mData.get(position).getSearch());
                }
            }
        });
        holder.ivDelete.setOnClickListener(view -> {
            if (callBack != null) {
                callBack.onClick(2, mData.get(position));
            }
        });
    }

    public void setData(List<SearchHistoryInfoBean> data) {
        if (mData != null) {
            mData.clear();
            mData.addAll(data);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    class BaseViewHolder extends RecyclerView.ViewHolder {
        TextView tvContent;
        ImageView ivDelete;

        public BaseViewHolder(View itemView) {
            super(itemView);
            tvContent = itemView.findViewById(R.id.tv_content);
            ivDelete = itemView.findViewById(R.id.iv_delete);
        }
    }
}
